import axios, {
    type AxiosInstance,
    type AxiosResponse,
} from 'axios'
import merge from 'lodash/merge'
import qs from 'qs'
import {ElMessage} from 'element-plus'

const BASE_URL: string = window.config.baseUrl

const http: AxiosInstance = axios.create({
    timeout: 1000 * 60,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})
http.interceptors.response.use(
    (response: AxiosResponse) => {
        // 如果响应是二进制流，则直接返回，用于下载文件、Excel 导出等
        if (response.config.responseType === 'blob') {
            return response
        }
        const {code, resultData, message} = response.data as ResponseData
        if (code === 0) {
            return resultData
        }
        if (code === -1) {
            ElMessage.error(message || '操作失败')
            return Promise.reject(new Error(message || 'Error'))
        }
        return response
    },
    (error) => {
        return Promise.reject(error)
    }
)
function buildUrl(path: string, params?: Record<string, any>, joinKey: string = '?') {
    let url = BASE_URL + path
    if (params && Object.keys(params).length > 0) {
        url += joinKey
        const keys: Array<string> = Object.keys(params)
        for (let i = 0; i < keys.length; i++) {
            if (i > 0) {
                url += '&'
            }
            const key = keys[i]
            const value = params[key]
            url += key + '=' + value
        }
    }
    return url
}
function adornParams(params: object, openDefaultParams: boolean = true) {
    const defaultParams: Record<string, any> = {
        t: new Date().getTime()
    }
    return openDefaultParams ? merge(defaultParams, params) : params
}
function adornData(data: object, contentType: string = 'json') {
    return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}

export {
    buildUrl,
    adornParams,
    adornData
}
export default http